//
//  ST_LiveP2PViewController.swift
//  btvideo
//
//  Created by Jason on 2021/12/20.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyJSON
import MJRefresh
import SwiftyUserDefaults
import RxSwift


class ST_LiveP2PViewController: UIViewController ,ST_VMControllerLightNavBarProduce {
    
    lazy var tain_navigation_bar:ST_TIANLightNavigationBar = {
        let c = ST_TIANLightNavigationBar()
        c.title_nav_btn.setTitleForAllStates("房间")
        c.backgroundColor = .clear

        c.left_nav_btn.setImage(ST_ImageUtils.imageName("navigation_left_bar_beauty"), for: .normal)
        c.left_nav_btn.snp.remakeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.centerY.equalTo(c.title_nav_btn)
            make.width.equalTo(64)
            make.height.equalTo(25)
        }
        
        c.right_nav_btn.alpha = 0
        c.addSubview(right_nav_btn)
        right_nav_btn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-15)
            make.centerY.equalTo(c.title_nav_btn)
            make.width.equalTo(68)
            make.height.equalTo(25)
        }
        
        return c
    }()
    
    
    lazy var right_nav_btn:ST_BTGradientButton = {
        
        let control = ST_BTGradientButton(frame: .zero)
        control.cornerRadius = 12
        control.bgLayer.startPoint = CGPoint(x: 0, y: 0.5)
        control.bgLayer.endPoint = CGPoint(x: 1, y: 0.5)
        control.modify_colors(colors: [UIColor(hex: 0x5AE2DA)!,UIColor(hex: 0x2DC6D3)!])
        control.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.semibold)
        control.setTitleColor(.white, for: .normal)
        control.setTitle("创建房间", for: .normal)
        control.addTarget(self, action: #selector(createParty), for: .touchUpInside)
        return control
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        
        defer{
            layout_navigation_bar()
        }
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets(top: 44+statusBarHeight, left: 0, bottom: 0, right: 0))
        }
        
        binding()
        
    }
    
    @objc fileprivate func insert_notification_handle(){
        
        //        不是已经插入了
        if let item = ST_LiveBeautyWidget.shared.my_create_room,self.data_array.first != item{
            self.data_array.insert(item, at: 0)
            self.collectionView.reloadData {
                guard let willPlayIdx = self.determined_will_play_index_path() else { return  }
                self.play(indexPath: willPlayIdx)
            }
        }else{
            //第一条是自己
            if self.data_array.first?.accid == ST_BTUserInfoManager.shared.current_account_info?.accid{
                self.data_array.remove(at: 0)
                
                self.pause_video()
                self.collectionView.reloadData()
            }
        }
        
        
    }
    
    @objc fileprivate func delete_notification(noti:Notification){
        
        let json = JSON(noti.userInfo ?? "")
        
        let accid = json["accid"].stringValue
        
        guard let removeIndex = data_array.firstIndex(where:({$0.accid == accid})) else{
            return
        }
        
        let index = Int(removeIndex.uInt)
        
        collectionView.performBatchUpdates({
            
            data_array.remove(at: index)
            
            collectionView.deleteItems(at: [IndexPath(row: index, section: 0)])
            
        }) { (f) in
            
            if self.data_array.count < 1{
                self.pause_video()
                self.collectionView.reloadData()
            }
            
            print("切换 显示 完毕")
            
        }
        
    }
    
    private func binding(){
        
        SCComponets.login_status_did_changed_observable().distinctUntilChanged().subscribe(onNext: { f in
            print("login_status_did_changed_observable subscribe -- ST_LiveP2PViewController")
            if f == true{
                self.refresh_data()
            }else{
                self.clear_data()
            }
        }).disposed(by: rx.disposeBag)
        
        NotificationCenter.default.rx.notification(ST_LiveBeautyWidget.delete_live_queue_notification, object: nil).withUnretained(self).subscribe(onNext: { own,noti in
            
            own.delete_notification(noti:noti)
            
        }).disposed(by: rx.disposeBag)
        
        
        
        
        NotificationCenter.default.rx.notification(Notification.Name.InsertMyCreateRoom, object: nil).withUnretained(self).subscribe(onNext: { own,_ in
            
            own.insert_notification_handle()
            
        }).disposed(by: rx.disposeBag)
        
        
        
        collectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            self.refresh_data()
        })
    }
    
    private func refresh_data() {
        
        self.currentPage = 0
        
        self.request_data()
        
    }
    
    private func clear_data() {
        self.header_data_array.removeAll()
        self.data_array.removeAll()
        self.pause_video()
        self.collectionView.reloadData()
    }
    
    
    fileprivate var header_data_array = [ST_MsgBannerHeaderCellModel]()
    
    fileprivate var first = true
    
    fileprivate var currentPage = 0
    
    fileprivate func request_data(){
        
        currentPage += 1
        
        let param = ["page":currentPage,"size":20]
        
        if currentPage == 1{
            
            Observable.zip(TIANSession(requestUrl: PH.fetchBannerApi, parameters: ["location":3]), TIANSession(requestUrl: PH.roomRecommendLiveApi, parameters: param)).withUnretained(self).subscribe(onNext: { own,arg in
                
                switch arg.0{
                case .success(let json):
                    own.header_data_array = json["data"].arrayValue.map({ ST_MsgBannerHeaderCellModel(fromJson: $0) })
                case .failure:
                    own.header_data_array = []
                    break
                }
                
                own.data_array_recommended_handle(result: arg.1)
                
            }).disposed(by: rx.disposeBag)
            
        }else{
            
            TIANSession(requestUrl: PH.roomRecommendLiveApi, parameters: param).withUnretained(self).subscribe(onNext: { own,res in
                
                own.data_array_recommended_handle(result: res)
                
            }).disposed(by: rx.disposeBag)
        }
        
    }
    
    
    private func data_array_recommended_handle(result:Result<JSON,ST_NetworkError>){
        
        
        
        self.first = false
        
        let array:[ST_LiveBeautyCellModel]
        
        switch result {
        case .success(let json):
            array = json["data"].arrayValue.map({ST_LiveBeautyCellModel.init(fromJson: $0)})
        case .failure(let err):
            self.toast(text: err.e)
            array = []
        }
        
        if self.currentPage == 1{
            self.data_array = array
            if let item = ST_LiveBeautyWidget.shared.my_create_room{
                self.data_array.insert(item, at: 0)
            }
        }else{
            self.data_array += array
        }
        
        self.collectionView.reloadData {
            guard let willPlayIdx = self.determined_will_play_index_path() else { return  }
            self.play(indexPath: willPlayIdx)
        }
        
        
        self.load_more_option_style(tableView: self.collectionView, count: array.count, pageSize: 20) {[weak self] in
            
            self?.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in
                
                self?.request_data()
            })
        }
        
        self.collectionView.mj_footer?.endRefreshing()
        
        self.collectionView.mj_header?.endRefreshing()
        
    }
    
    //    MARK: - Properties
    
    fileprivate lazy var layout:UICollectionViewFlowLayout = {
        let controlLayout = UICollectionViewFlowLayout()
        controlLayout.minimumLineSpacing = 11
        controlLayout.minimumInteritemSpacing = 11
        controlLayout.sectionInset = UIEdgeInsets.init(top: 10, left: 15, bottom: BTSafeAreaBottom + 49, right: 15)
        let w = (ScreenWidth - 15*2 - 11*2)/2
        controlLayout.itemSize = CGSize.init(width: w, height: w/168.0*190)
        
        return controlLayout
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: ST_LiveP2pCollectionCell.self)
        control.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: ST_LiveP2PHeaderView.self)
        
        control.emptyDataSetSource = self
        control.emptyDataSetDelegate = self
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.backgroundColor = UIColor.white
        control.alwaysBounceVertical = true
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        return control
    }()
    
    
    
    fileprivate(set) lazy var data_array = [ST_LiveBeautyCellModel]()
    
    //    MARK:- Player View
    fileprivate lazy var playerView:ST_PeculiarityVideoPlayView = {
        let control = ST_PeculiarityVideoPlayView()
        control.isUserInteractionEnabled = false
        control.backgroundColor = .clear
        control.clipsToBounds = true
        control.isMuted = true
        control.loopPlay = true
        
        return control
    }()
    
    fileprivate var current_play_index_path:IndexPath?
    
    fileprivate lazy var containerRect = CGRect.init(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight)
}


//MARK: -
extension ST_LiveP2PViewController:UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        
        if header_data_array.count == 0{
            return CGSize.zero
        }else{
            return CGSize(width: ScreenWidth, height: 81+4)
        }
        
    }
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data_array.count
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_LiveP2pCollectionCell.self, for: indexPath)
        
        cell.model = data_array[safe:indexPath.row]
        
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        guard let model = data_array[safe:indexPath.row] else { return  }
        
        invite_chat_action(cellModel: model)
        
    }
    
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withClass: ST_LiveP2PHeaderView.self, for: indexPath)
        
        view.data_array = self.header_data_array
        
        return view
    }
    
    
    
    //    MARK: Scroll Delegate
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        //        判断当前正在播放的cell 在显示吗
        if let curr = current_play_index_path,let cell = collectionView.cellForItem(at: curr){
            
            let rectInScreen = collectionView.convert(cell.frame, to: nil)
            
            if containerRect.intersects(rectInScreen) == false{
                pause_video()
            }
        }
    }
    
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
        
        if !decelerate{
            scrollviewdidEndScroll(scrollView)
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        scrollviewdidEndScroll(scrollView)
        
    }
    
    //    MARK: 停止滚动
    func scrollviewdidEndScroll(_ scrollView:UIScrollView){
        
        guard let willPlayIdx = determined_will_play_index_path() else {
            
            pause_video()
            
            return
        }
        
        if let curr = current_play_index_path,curr.item == willPlayIdx.item{
            return
        }
        
        play(indexPath: willPlayIdx)
        
    }
    
}




extension ST_LiveP2PViewController:DZNEmptyDataSetSource,DZNEmptyDataSetDelegate{
    
    func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView!) -> Bool {
        return true
    }
    
    func emptyDataSetShouldDisplay(_ scrollView: UIScrollView!) -> Bool {
        
        if first{
            self.first = false
            return false
        }else{
            return true
        }
    }
    
    func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        
        var str = "当前没有小姐姐接受速配邀请哦\n晚点再来看看"
        
        if let user = ST_BTUserInfoManager.shared.current_account_info?.userinfo ,user.sex == .female {
            str = "小哥哥们太腼腆，主动去邀约心仪\n的小哥通话吧"
        }
        
        let attrString = NSMutableAttributedString(string: str)
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 16),.foregroundColor: UIColor.init(hex: 0xCDD1DB)!]
        
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        
        return attrString
    }
    
    func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        
        return ST_ImageUtils.imageName("首页_img_gift_empty")
    }
}


extension ST_LiveP2PViewController:ST_TIANLightNavigationBarAction{
    
    func navigation_item_bar_tap_subscribe(position:ST_TIANLightNavigationBarItemPosition){
        
        switch position {
        case .left:
            push_setting_beauty_filter_controller()
        case .right:
            createParty()
        case .center:
            break
        }
        
    }
    
    @objc fileprivate func createParty(){
        
        let operationStr = "创建房间"
        
        switch ST_BTUserInfoManager.shared.app_chat_status_behavior.value {
        case .none:
            
            let alert = ST_JoinRoomOptionsController()
            
            alert.overCurrentContext = true
            
            alert.over_current_context_alpha = "0.4"
            
            GlobalPresent(toController: alert)
            
        case .fallInVoiceQueue:
            
            self.toast(text: "等待语音匹配中，退出后才可\(operationStr)哦")
            
        case .fallInVideoQueue:
            
            
            self.toast(text: "等待视频匹配中，退出后才可\(operationStr)哦")
            
        case .invitingP2P:
            
            self.toast(text: "等待聊天中，退出后才可\(operationStr)哦")
            
        case .talkingP2P:
            
            self.toast(text: "聊天中，退出后才可\(operationStr)哦")
            
        case .waitingRespP2P:
            
            self.toast(text: "接受邀请中，退出后才可\(operationStr)哦")
            
        case .inVoiceChatGroup:
            
            self.toast(text: "派对中，退出后才可\(operationStr)哦")
        }
        
        
    }
    
    
    fileprivate func push_setting_beauty_filter_controller(){
        
        //        print("跳转美颜设置")
        if ST_TIANEngagementManager.defaultManager.engagement_entiy != nil{
            
            TopmostViewController()?.toast(text: "正在通话，请稍后再试")
            
            return
        }
       
        
        self.tain_navigation_bar.left_nav_btn.isUserInteractionEnabled = false
        
        main_thread_execute(afterDelay: 1.5) {
            self.tain_navigation_bar.left_nav_btn.isUserInteractionEnabled = true
        }
        
        GlobalPresent(toController: ST_SettingBeautyFIlterController())
        
        
    }
    
    
    @objc fileprivate func invite_chat_action(cellModel:ST_LiveBeautyCellModel){
        
        if cellModel.state == 3{
            self.toast(text: "啊哦~对方正在忙哦")
            return
        }
        
        if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self) {
            return
        }
        
        
        let isVideo:Bool = cellModel.type == 2
        
        if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == cellModel.sex,let str = SCComponets.rich_text_storage_component.json["limitations"]["cot"].string,str.count > 2{
            
            self.toast(text: str)
            
            return
        }
        
        
        ST_MediaChatDispatcher.shared.inviteChat(sessionId: cellModel.accid, isVideo: isVideo,inviteDistract: "upLiveWall")
        
    }
    
}



extension ST_LiveP2PViewController{
    
    
    /**
     找出可以播放的indexPath
     */
    fileprivate func find_can_play_index_path(determineContinueBlock:((UICollectionViewCell)->(Bool)))->IndexPath?{
        
        var foundIndex:IndexPath?
        
        for cell in collectionView.visibleCells {
            
            if determineContinueBlock(cell){
                continue
            }
            
            guard let playIdx = collectionView.indexPath(for: cell),let item_model = data_array[safe: playIdx.row],let url = item_model.roomCover?.videoUrl,url.count > 2 else { continue }
            
            if let last = foundIndex,last.item < playIdx.item{
                continue
            }
            
            let rectInScreen = collectionView.convert(cell.frame, to: nil)
            
            let intersect = containerRect.intersection(rectInScreen)
            
            let percent = (intersect.width * intersect.height)/(rectInScreen.width * rectInScreen.height)
            //               小于 70% 换下一个哈
            if percent < 0.8{
                continue
            }
            
            foundIndex = playIdx
            
            //            }
        }
        
        return foundIndex
    }
    
    /**
     确定播放下一个indexPath
     */
    fileprivate func determined_will_play_index_path()->IndexPath?{
        
        var foundIndex:IndexPath?
        
        //        判断当前正在播放的cell 在显示吗
        if let curr = current_play_index_path,let currCell = collectionView.cellForItem(at: curr){
            
            let rectInScreen = collectionView.convert(currCell.frame, to: nil)
            
            let intersect = containerRect.intersection(rectInScreen)
            
            let percent = (intersect.width * intersect.height)/(rectInScreen.width * rectInScreen.height)
            //               大于 50% 还是展示自己
            if percent > 0.5{
                return curr
            }else{
                foundIndex = find_can_play_index_path(determineContinueBlock: { (item) -> (Bool) in
                    return item == currCell
                })
            }
        }else{
            
            // 取出第一个 video cell 播放
            foundIndex = find_can_play_index_path(determineContinueBlock: { (item) -> (Bool) in
                return false
            })
        }
        
        //        print("Bug 10000-将要切换到另外一个Item :",foundIndex)
        
        return foundIndex
    }
    
    
    
    
    fileprivate func play(indexPath:IndexPath){
        
        pause_video()
        
        
        guard let cell = collectionView.cellForItem(at: indexPath) as? TianCellFollowPlayProtocol , let dataItem = data_array[safe:indexPath.item],let urlStr = dataItem.roomCover?.videoUrl ,let url = URL(string: urlStr) else{return}
        
        cell.padding(playView: playerView)
        
        playerView.play(url: url )
        
        current_play_index_path = indexPath
    }
    
    fileprivate func pause_video(){
        
        playerView.stop()
        
        if playerView.superview != nil {
            playerView.removeFromSuperview()
        }
        
        current_play_index_path = nil
    }
    
}

